// planet-detail.js - 星球详情页面
const { getUserPlanets } = require('../../utils/cloud');
const { safePageInit, handleError } = require('../../utils/error-handler');

Page({
  // 页面路由信息
  route: 'pages/planet-detail/planet-detail',
  
  data: {
    planetId: '',
    planetName: '',
    planetDescription: '',
    planetColor: '',
    planetTags: [],
    dreams: [],
    dreamCount: 0,
    createTime: '',
    analysisData: null
  },

  onLoad(options) {
    safePageInit(this, () => {
      const { planetId, planetName } = options;
      this.setData({
        planetId: planetId || '',
        planetName: planetName || '未知星球'
      });
      
      this.loadPlanetData();
    });
  },

  // 加载星球数据
  async loadPlanetData() {
    try {
      const dreams = await getUserPlanets();
      const planetDreams = dreams.filter(dream => dream.planetType === this.data.planetId);
      
      if (planetDreams.length === 0) {
        this.setData({
          dreams: [],
          dreamCount: 0,
          planetDescription: '这个星球还没有梦境记录',
          planetColor: 'linear-gradient(135deg, #696969 0%, #a9a9a9 100%)',
          planetTags: [],
          createTime: '未知'
        });
        return;
      }

      const firstDream = planetDreams[0];
      const tags = new Set();
      planetDreams.forEach(dream => {
        if (dream.tags) {
          dream.tags.forEach(tag => tags.add(tag));
        }
      });

      this.setData({
        dreams: planetDreams.map(dream => ({
          ...dream,
          date: this.formatDate(dream.date),
          time: this.formatTime(dream.date),
          emotion: this.getEmotionIcon(dream.emotions)
        })),
        dreamCount: planetDreams.length,
        planetDescription: firstDream.description || this.getPlanetDescription(this.data.planetId),
        planetColor: firstDream.color || this.getPlanetColor(this.data.planetId),
        planetTags: Array.from(tags),
        createTime: this.formatDate(firstDream.date),
        analysisData: this.generateAnalysisData(planetDreams)
      });
    } catch (error) {
      handleError(this, '加载星球数据失败', error);
    }
  },

  // 生成分析数据
  generateAnalysisData(dreams) {
    if (dreams.length === 0) return null;

    // 统计情绪
    const emotionCount = {};
    dreams.forEach(dream => {
      if (dream.emotions) {
        Object.entries(dream.emotions).forEach(([emotion, value]) => {
          emotionCount[emotion] = (emotionCount[emotion] || 0) + value;
        });
      }
    });

    const mainEmotion = Object.keys(emotionCount).reduce((a, b) => 
      emotionCount[a] > emotionCount[b] ? a : b, '未知'
    );

    // 计算频率
    const frequency = dreams.length > 10 ? '高频' : dreams.length > 5 ? '中频' : '低频';

    // 提取关键词
    const allTags = [];
    dreams.forEach(dream => {
      if (dream.tags) {
        allTags.push(...dream.tags);
      }
    });
    const keywordCount = {};
    allTags.forEach(tag => {
      keywordCount[tag] = (keywordCount[tag] || 0) + 1;
    });
    const keywords = Object.keys(keywordCount)
      .sort((a, b) => keywordCount[b] - keywordCount[a])
      .slice(0, 3)
      .join('、');

    return {
      mainEmotion,
      frequency,
      keywords: keywords || '无'
    };
  },

  // 查看梦境详情
  viewDreamDetail(e) {
    const dream = e.currentTarget.dataset.dream;
    wx.navigateTo({
      url: `/pages/dream-detail/dream-detail?id=${dream._id}`
    });
  },

  // 添加梦境到星球
  addDreamToPlanet(e) {
    console.log('点击添加梦境按钮', e);
    wx.navigateTo({
      url: `/dream-wormhole-master/pages/index/index?planetType=${this.data.planetId}`
    });
  },

  // 分享星球
  sharePlanet(e) {
    console.log('点击分享星球按钮', e);
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    
    wx.showToast({
      title: '请使用右上角分享',
      icon: 'none',
      duration: 2000
    });
  },

  // 3D探索星球
  explorePlanet3D(e) {
    console.log('点击3D探索按钮', e);
    const planetData = {
      planetId: this.data.planetId,
      planetName: this.data.planetName,
      planetColor: this.data.planetColor,
      planetEmoji: this.getPlanetEmoji(this.data.planetId)
    };
    
    wx.navigateTo({
      url: `/dream-wormhole-master/pages/planet-explore/planet-explore?planetId=${planetData.planetId}&planetName=${planetData.planetName}&planetColor=${encodeURIComponent(planetData.planetColor)}&planetEmoji=${planetData.planetEmoji}`
    });
  },

  // 获取星球emoji
  getPlanetEmoji(planetType) {
    const emojis = {
      '飞翔星球': '🦅',
      '海洋星球': '🌊',
      '森林星球': '🌲',
      '迷宫星球': '🌑',
      '城市星球': '🏙️',
      '奇幻星球': '✨',
      '恐怖星球': '👻',
      '童年星球': '🎈'
    };
    return emojis[planetType] || '🌍';
  },

  // 返回
  onBack() {
    wx.navigateBack();
  },

  // 格式化日期
  formatDate(dateStr) {
    const date = new Date(dateStr);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) return '今天';
    if (days === 1) return '昨天';
    if (days < 7) return `${days}天前`;
    
    return date.toLocaleDateString('zh-CN');
  },

  // 格式化时间
  formatTime(dateStr) {
    const date = new Date(dateStr);
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  },

  // 获取情绪图标
  getEmotionIcon(emotions) {
    if (!emotions || !Array.isArray(emotions) || emotions.length === 0) return '😐';
    
    const emotion = emotions[0];
    if (typeof emotion === 'object' && emotion !== null) {
      const emotionStr = emotion.name || emotion.value || emotion.text || '';
      return this.getEmotionEmoji(emotionStr);
    }
    
    return this.getEmotionEmoji(String(emotion || ''));
  },

  // 获取情绪表情
  getEmotionEmoji(emotion) {
    if (emotion.includes('快乐') || emotion.includes('开心') || emotion.includes('高兴')) return '😊';
    if (emotion.includes('悲伤') || emotion.includes('难过') || emotion.includes('伤心')) return '😢';
    if (emotion.includes('恐惧') || emotion.includes('害怕') || emotion.includes('惊恐')) return '😨';
    if (emotion.includes('愤怒') || emotion.includes('生气') || emotion.includes('恼火')) return '😠';
    if (emotion.includes('惊讶') || emotion.includes('震惊') || emotion.includes('吃惊')) return '😲';
    if (emotion.includes('平静') || emotion.includes('安静') || emotion.includes('平和')) return '😌';
    if (emotion.includes('兴奋') || emotion.includes('激动') || emotion.includes('兴奋')) return '🤩';
    
    return '😐';
  },

  // 获取星球描述
  getPlanetDescription(planetType) {
    const descriptions = {
      'happy': '充满欢乐与正能量的梦境世界',
      'sad': '承载着情感与回忆的梦境空间',
      'fear': '探索内心恐惧的梦境领域',
      'anger': '释放情绪与力量的梦境世界',
      'surprise': '充满意外与惊喜的梦境空间',
      'calm': '宁静平和的梦境港湾',
      'excitement': '充满激情与活力的梦境世界',
      'love': '温暖浪漫的梦境空间',
      'adventure': '充满冒险与探索的梦境世界',
      'mystery': '神秘莫测的梦境领域',
      'unknown': '等待探索的神秘梦境空间'
    };
    return descriptions[planetType] || descriptions['unknown'];
  },

  // 获取星球颜色
  getPlanetColor(planetType) {
    const colors = {
      'happy': 'linear-gradient(135deg, #ffd700 0%, #ffed4e 100%)',
      'sad': 'linear-gradient(135deg, #4a90e2 0%, #7bb3f0 100%)',
      'fear': 'linear-gradient(135deg, #8b0000 0%, #dc143c 100%)',
      'anger': 'linear-gradient(135deg, #ff4500 0%, #ff6347 100%)',
      'surprise': 'linear-gradient(135deg, #ff69b4 0%, #ffb6c1 100%)',
      'calm': 'linear-gradient(135deg, #87ceeb 0%, #b0e0e6 100%)',
      'excitement': 'linear-gradient(135deg, #ff1493 0%, #ff69b4 100%)',
      'love': 'linear-gradient(135deg, #ff69b4 0%, #ff1493 100%)',
      'adventure': 'linear-gradient(135deg, #32cd32 0%, #90ee90 100%)',
      'mystery': 'linear-gradient(135deg, #9370db 0%, #ba55d3 100%)',
      'unknown': 'linear-gradient(135deg, #696969 0%, #a9a9a9 100%)'
    };
    return colors[planetType] || colors['unknown'];
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  },

  // 返回主界面
  goToHome() {
    wx.reLaunch({
      url: '/dream-wormhole-master/pages/index/index'
    });
  }
});


